package com.longqinuo.mycarservice.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.longqinuo.mycarservice.entity.SecondCar;
import com.longqinuo.mycarservice.manager.DatabaseOpenHelper;


/**
 * dao层实现类 使用SQLiteDatabase对象增删改查
 * Created by zxw on 2016/5/20.
 */
public class DaoImpl implements IDao {
    private SQLiteDatabase database;
    public DaoImpl(Context context) {
        DatabaseOpenHelper helper = new DatabaseOpenHelper(context);
        database = helper.getWritableDatabase();
    }
    @Override
    public long add(SecondCar s) {

        long result = 0;
        if (!isExists(s.getId())) {
            ContentValues values = new ContentValues();
            values.put("car_Id",s.getId());
            values.put("title",s.getTitle());
            values.put("image",s.getImage());
            values.put("km",s.getKm());
            values.put("buy_date",s.getBuyDate());
            values.put("price",s.getPrice());
            values.put("tab",s.getTab());
            result = database.insert(DatabaseOpenHelper.TABLE_NAME,null,values);
        }

        return result;
    }

    @Override
    public boolean isExists(int carId) {
        Cursor cursor = database.query(DatabaseOpenHelper.TABLE_NAME,null,"car_Id = ?",new String[]{carId+""},null,null,null);
        if (cursor!=null&&cursor.getCount()>0) {

            return true;
        } else {
            return false;
        }
    }
    @Override
    public Cursor findCar(SecondCar s) {
        Cursor cursor = database.query(DatabaseOpenHelper.TABLE_NAME,null,"car_Id = ?",new String[]{s.getId()+""},null,null,null);
        return cursor;
    }

    @Override
    public Cursor findAllCars() {
        Cursor cursor = database.query(DatabaseOpenHelper.TABLE_NAME,null,null,null,null,null,null);
        return cursor;
    }

    @Override
    public int delete(SecondCar s) {
        int i = database.delete(DatabaseOpenHelper.TABLE_NAME,"car_Id = ?",new String[]{s.getId()+""});
        return i;
    }
}
